<script setup>
import TailPrice from "@/components/TailPrice.vue";
import {onMounted, inject, watchEffect, ref} from 'vue'
import {
  CANCEL,
  getOrderStatusMsg,
  WAIT_COMMENT,
  WAIT_DELIVERY,
  WAIT_PAY,
  WAIT_RECEIVE
} from "@/constants/OrderStatus.js";
import {ORDER_DETAIL_ROUTE} from "@/router/routes/order/OrderDetail.js";
import {useRoute, useRouter} from "vue-router";
import {cancelOrderAPI, getAllOrderAPI, payOrderAPI, updateOrderAPI} from "@/api/order.js";
import useOrderStore from "@/store/modules/OrderStore.js";
import {showConfirmDialog} from "vant";
import 'vant/es/dialog/style'
import {getProductById} from "@/api/product.js";
import {elErrorMessageTip, elSuccessMessageTip} from "@/utils/MessageTipUtils.js";
import {COMMENT_ROUTE} from "@/router/routes/order/comment.js";

const route = useRoute()
const router = useRouter()

const {getOrderList} = inject('order')
const props = defineProps({
  order: {type: Object, default: {}}
})

const getAllPrice = () => {
  props.order.allPrice = props.order?.productOptionPrice * props.order.num + props.order.freight
  props.order.allPrice = Math.round(props.order.allPrice * 100) / 100
}
onMounted(() => {
  getAllPrice()
})
// watchEffect(() => {
//   props.order.allPrice = props.order?.productOptionPrice * props.order.num + props.order.freight
//   props.order.allPrice = Math.round(props.order.allPrice * 100) / 100
// })

const goOrderDetail = () => {
  router.push({name: ORDER_DETAIL_ROUTE, query: {orderId: props.order.id}})
}

const onCancelOrder = async () => {
  showConfirmDialog({
    message: '是否确认取消订单'
  }).then(async () => {
    // on confirm
    let res = null
    if (props.order.status === WAIT_PAY) {
      res = await updateOrderAPI(props.order.id, CANCEL)
    } else {
      res = await cancelOrderAPI(props.order.id, CANCEL)
    }
    if (res) {
      useOrderStore().saveAll(await getAllOrderAPI())
      getOrderList()
    }
  }).catch(() => {
    // on cancel
  });
}

const floatPanelVisible = ref(false)
const anchors = ref([window.innerHeight * 0.85])
const newProductOptionId = ref(0)
const onOpenPanel = async () => {
  floatPanelVisible.value = true
}
const onClosePanel = () => {
  floatPanelVisible.value = false
}
const payByWe = ref(false)
const payByAli = ref(false)
const onOpenPayByWe = () => {
  payByWe.value = true
}
const onOpenPayByAli = () => {
  payByAli.value = true
}
const payHandler = async () => {
  const res = await payOrderAPI(props.order.id, WAIT_DELIVERY)
  if (!res.status) {
    elErrorMessageTip(res.msg)
    return
  }
  elSuccessMessageTip("订单支付成功")
  useOrderStore().saveAll(await getAllOrderAPI())
  getOrderList()
  onClosePanel()
}
const onClosePayByWe = () => {
  payByWe.value = false
  payHandler()
}
const onClosePayByAli = () => {
  payByAli.value = false
  payHandler()
}

const onReceiveOrder = async () => {
  showConfirmDialog({
    message: '是否确认收货'
  }).then(async () => {
    // on confirm
    let res = await updateOrderAPI(props.order.id, WAIT_COMMENT)
    if (res) {
      useOrderStore().saveAll(await getAllOrderAPI())
      getOrderList()
    }
  }).catch(() => {
    // on cancel
  });
}

const goComment = () => {
  router.replace({name: COMMENT_ROUTE, query: {orderId: props.order.id}})
}
</script>

<template>
  <div class="order-item mb-2 ml-2 mr-2 pb-2 rounded-lg bg-white dark:bg-neutral-900">
    <div class="product-info p-1 pl-2 flex justify-start items-stretch"
         @click="goOrderDetail"
    >
      <div class="option-img w-1/6 mr-2 rounded-xl overflow-hidden"
      >
        <img class="w-full h-full object-contain" :src="order?.productOptionImg" alt="">
      </div>
      <div class="pt-1 w-9/12">
        <div class="truncate dark:text-gray-100"
        >{{ order?.title }}
        </div>
        <div
            class="option-name mt-1 mb-1 p-0.5 pl-2 pr-2 rounded-md bg-gray-300 truncate text-gray-500 text-xs"
        >{{ order?.productOptionName }}
        </div>
        <div class="flex justify-between items-center text-gray-500">
          <div class="flex-start-center text-sm">
            <div class="flex-start-center mr-1">
              <span>单价：</span>
              <TailPrice
                  :price="order?.productOptionPrice?.toString()"
                  :is-start="false"
              ></TailPrice>
            </div>
            <div>
              <span>数量：{{ order?.num }}</span>
            </div>
          </div>
          <div class="flex-start-center text-sm">
            <span>合计：</span>
            <TailPrice
                :price="order?.allPrice?.toString()"
                :is-start="false"
            ></TailPrice>
          </div>
        </div>
      </div>
    </div>
    <div class="mt-2 mr-2 flex justify-between">
      <div class="text-sm text-gray-500 flex-center pl-2">
        <span>{{ getOrderStatusMsg(order?.status) }}</span>
      </div>
      <div class="flex-center">
        <van-button
            v-if="order?.status === WAIT_PAY || order?.status === WAIT_DELIVERY"
            type="primary" size="mini"
            color="linear-gradient(to right, #d1d5db, #909399cc, #d1d5db)"
            @click="onCancelOrder"
        >取消订单
        </van-button>
        <van-button
            v-if="order?.status === WAIT_PAY"
            type="primary" size="mini"
            color="linear-gradient(to right, #ee0a24, #ff6034, #ee0a24)"
            @click="onOpenPanel"
        >支付订单
        </van-button>
        <van-button
            v-if="order?.status === WAIT_RECEIVE"
            type="primary" size="mini"
            @click="onReceiveOrder"
            color="linear-gradient(to right, #5f88ff, #1989fa, #5f88ff)"
        >确认收货
        </van-button>
        <van-button
            v-if="order?.status === WAIT_COMMENT"
            type="primary" size="mini"
            @click="goComment"
            color="linear-gradient(to right, #1989fa, #17a6f8, #1989fa)"
        >商品评价
        </van-button>
      </div>
    </div>
    <van-overlay :show="floatPanelVisible" @click="onClosePanel" lock-scroll></van-overlay>
    <van-floating-panel
        :content-draggable="true"
        :anchors="anchors"
        v-show="floatPanelVisible"
    >
      <div class="p-2 flex justify-end items-center">
        <div class="mr-4 text-neutral-600 dark:text-gray-200" @click="onClosePanel">
          <span class="iconfont icon-close"></span>
        </div>
      </div>
      <van-cell title="微信支付" is-link @click="onOpenPayByWe"/>
      <van-cell title="支付宝" is-link @click="onOpenPayByAli"/>
      <van-overlay :show="payByWe" @click="onClosePayByWe">
        <div class="w-screen h-screen flex-center">
          <div class="w-56 rounded-2xl overflow-hidden" @click.stop>
            <img class="w-full h-full object-contain" src="@/assets/imgs/PayByWeChat.png" alt="">
          </div>
        </div>
      </van-overlay>
      <van-overlay :show="payByAli" @click="onClosePayByAli">
        <div class="w-screen h-screen flex-center">
          <div class="w-56 rounded-2xl overflow-hidden" @click.stop>
            <img class="w-full h-full object-contain" src="@/assets/imgs/PayByAli.jpg" alt="">
          </div>
        </div>
      </van-overlay>
    </van-floating-panel>
  </div>
</template>

<style scoped lang="scss">
.product-info {
  border-bottom: 1px solid #d0cece;
}

.product-option {
  border: 1px solid transparent;
  font-weight: 300;
}

.product-option-selected {
  border: 1px solid #ff5000;
}

.option-img {
  min-width: 4.5rem;
  max-width: 6rem;
}

.option-name {
  width: min-content;
  max-width: 70%;
}
</style>